package controller;

import databaseLayer.ManagerUpdate;
import databaseLayer.MoviesLookUp;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import movieBean.Movie;
import movieBean.MovieSlot;
import movieBean.SeatPlan;
import movieBean.SingleMovie;
import pageBean.ManagerModifyPage;
import userBean.UserIdentity;

/**
 *
 * @author Sam
 */
public class ModifyMovie extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String topDisplayMsg = "";
        String address = "/modifyTimeSlot.jsp";
        
        HttpSession session = request.getSession();
        if (session.isNew() || !(((UserIdentity)session.getAttribute("userIdentity")).getUserType().equals("TicketingManager"))) {
            if (session.isNew()) {
                session.invalidate();
            }
            
            address = "index.do";
        }
        else {
            String movieName = request.getParameter("movie");
            String slotID = request.getParameter("slotID");
            
            if ((movieName == null || movieName == "") || (slotID == null || slotID == "")) {
                address = "Manage.do";
            }
            else {
                Date currentTime = new Date();
                SimpleDateFormat timeZoneFormatter = new SimpleDateFormat("z");
                String timeZone = timeZoneFormatter.format(currentTime);

                String initialTime = "0000/00/00 00:00:00 " + timeZone;
                String endTime = "9999/99/99 23:59:59 " + timeZone;
                System.out.println("movieName: " + movieName);

                Movie allThisMovie = MoviesLookUp.getMovie(movieName, initialTime, endTime);
                System.out.println(allThisMovie);
                SingleMovie thisMovie = new SingleMovie();
                int arrIndex = -1;
                for (int i = 0; i < allThisMovie.getMovieSlot().length; i++) {
                    if ((allThisMovie.getMovieSlot())[i].getSlotID().equals(slotID)) {
                        arrIndex = i;
                        thisMovie.setName(allThisMovie.getName());
                        thisMovie.setDescription(allThisMovie.getDescription());
                        thisMovie.setDuration(allThisMovie.getDuration());
                        thisMovie.setMovieSlot((allThisMovie.getMovieSlot())[i]);
                        thisMovie.setThumbnailPath(allThisMovie.getThumbnailPath());
                        thisMovie.setTrailerPath(allThisMovie.getTrailerPath());
                        break;
                    }
                }

                int houseNo = thisMovie.getMovieSlot().getHouse();
                String includeHouse = "/house" + houseNo + ".jsp";
                SeatPlan thisSeatPlan = MoviesLookUp.getSeatPlan(slotID);

                ManagerModifyPage displayControl = new ManagerModifyPage();
                boolean inThePast = false;
                boolean noOneBuy = true;

                SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy'/'MM'/'dd HH:mm:ss z");
                try {
                    System.out.println(dateFormatter.format(currentTime));
                    System.out.println(thisMovie.getMovieSlot().getStartTime());
                    Date movieShowTime = dateFormatter.parse(thisMovie.getMovieSlot().getStartTime());
                    if (movieShowTime.before(currentTime)) {
                        inThePast = true;
                    }
                } catch (ParseException ex) {
                    Logger.getLogger(ModifyMovie.class.getName()).log(Level.SEVERE, null, ex);
                }

                for (int i = 0; i < thisSeatPlan.getSeat().length; i++) {
                    if ((thisSeatPlan.getSeat())[i].equals("boughtSeat")) {
                        noOneBuy = false;
                        break;
                    }
                }

                System.out.println(inThePast);
                if (!inThePast && noOneBuy) {
                    displayControl.setShowTimeInput(true);
                    displayControl.setChangeSTButton(true);
                    displayControl.setRemoveSTButton(true);
                    displayControl.setPriceInput(true);
                    displayControl.setChangePButton(true);
                }
                else {
                    displayControl.setShowTimeInput(false);
                    displayControl.setChangeSTButton(false);
                    displayControl.setRemoveSTButton(false);

                    if (inThePast) {
                        displayControl.setPriceInput(false);
                        displayControl.setChangePButton(false);
                    }
                    else {
                        displayControl.setPriceInput(true);
                        displayControl.setChangePButton(true);
                    }
                }

                String action = request.getParameter("action");
                System.out.println("action: " + action);
                if (action != null && action.equals("ChangeT")) {
                    if (!inThePast && noOneBuy) {
                        String showTimeStr = request.getParameter("showTime");
                        try {
                            Date newShowTime = dateFormatter.parse(showTimeStr);

                            GregorianCalendar tempCal = new GregorianCalendar();
                            int movieDuration = allThisMovie.getDuration();

                            if (arrIndex > 0) {
                                Date previousMovieST = dateFormatter.parse((allThisMovie.getMovieSlot())[arrIndex - 1].getStartTime());

                                tempCal.setTime(previousMovieST);
                                tempCal.add(GregorianCalendar.MINUTE, movieDuration);

                                if (newShowTime.before(tempCal.getTime())) {
                                    topDisplayMsg = "Time Conflict occurred! Show time cannot be chnaged!";
                                }
                            }

                            if (arrIndex < allThisMovie.getMovieSlot().length - 1) {
                                Date nextMovieST = dateFormatter.parse((allThisMovie.getMovieSlot())[arrIndex + 1].getStartTime());

                                tempCal.setTime(newShowTime);
                                tempCal.add(GregorianCalendar.MINUTE, movieDuration);

                                if (nextMovieST.before(tempCal.getTime())) {
                                    topDisplayMsg = "Time Conflict occurred! Show time cannot be chnaged!";
                                }
                            }

                            if (topDisplayMsg == null || topDisplayMsg == "") {
                                ManagerUpdate.changeMovieSlotStartTime(slotID, showTimeStr);

                                MovieSlot thisMovieSlot = thisMovie.getMovieSlot();
                                thisMovieSlot.setStartTime(showTimeStr);
                                thisMovie.setMovieSlot(thisMovieSlot);

                                topDisplayMsg = "Show time is updated successfully!";
                            }
                        } catch (ParseException ex) {
                            topDisplayMsg = "Show time's format is invalid!";
                        }
                    }
                    else {
                        topDisplayMsg = "Show time of this slot cannot be modified!";
                    }
                }
                else if (action != null && action.equals("remove")) {
                    if (!inThePast && noOneBuy) {
                        ManagerUpdate.removeMovieSlot(slotID);

                        topDisplayMsg = "One movie slot is removed successfully!";
                        session.setAttribute("topDisplayMsg", topDisplayMsg);

                        address = "Manage.do";
                    }
                    else {
                        topDisplayMsg = "This movie slot cannot be removed!";
                    }
                }
                else  if (action != null && action.equals("ChangeP")) {
                    System.out.println("here");
                    if (!inThePast) {
                        String newPriceStr = request.getParameter("price");

                        try {
                            int newPrice = Integer.parseInt(newPriceStr);

                            if (newPrice < 35) {
                                topDisplayMsg = "No movies can have price lower than $35!";
                            }
                            else {
                                ManagerUpdate.changeMovieSlotPrice(slotID, newPrice);

                                MovieSlot thisMovieSlot = thisMovie.getMovieSlot();
                                thisMovieSlot.setPrice(newPrice);
                                thisMovie.setMovieSlot(thisMovieSlot);

                                topDisplayMsg = "Price is updated successfully!";
                            }
                        }
                        catch (NumberFormatException e) {
                            topDisplayMsg = "Price is invalid!";
                        }
                    }
                    else {
                        topDisplayMsg = "Price of this slot cannot be modified!";
                    }
                }
                else  if (action != null && action.equals("ChangeS")) {
                    if (!inThePast) {
                        String seatNoStr = request.getParameter("seatNo");
                        int seatNo = Integer.parseInt(seatNoStr);

                        if ((thisSeatPlan.getSeat())[seatNo - 1].equals("boughtSeat")) {
                            topDisplayMsg = "The selected seat is already bought by customer!";
                        }
                        else {
                            ManagerUpdate.enableOrDisableSeat(slotID, seatNo);
                            thisSeatPlan = MoviesLookUp.getSeatPlan(slotID);
                            topDisplayMsg = "Seat plan is updated successfully!";
                        }
                    }
                    else {
                        topDisplayMsg = "Seat plan of this slot cannot be modified!";
                    }
                }

                request.setAttribute("thisMovie", thisMovie);
                request.setAttribute("topDisplayMsg", topDisplayMsg);
                request.setAttribute("thisSeatPlan", thisSeatPlan);
                request.setAttribute("displayControl", displayControl);
                request.setAttribute("includeHouse", includeHouse);

                address = address + "?house=" + houseNo;
            }
        }
        
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }
    
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
